package com.mcgrady.exception;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author McGrady
 */
public class ExceptionCatchTest {
    @Test
    public void tryCatchStructure() {
        int[] num = new int[5];
        try {
            num[5] = 1;
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("程序结束...");
        }
        System.out.println("如果异常爆发，我不会被输出...");
    }

    private int returnInTryOrCatchWithBase(int num) {
        try {
            System.out.println(100 / num);
            return 100;
        } catch (ArithmeticException e) {
            System.out.println("catch执行");
            return 200;
        } finally {
            System.out.println("finally执行");
            num = 300;
        }
    }

    private int[] returnInTryOrCatchWithReference(int num) {
        int[] arr = {0, 1};
        try {
            System.out.println(100 / num);
            arr[0] = 100;
            return arr;
        } catch (ArithmeticException e) {
            System.out.println("catch执行...");
            arr[0] = 200;
            return arr;
        } finally {
            System.out.println("finally执行...");
            arr[0] = 300;
        }
    }

    private int returnInTryOrCatchAndFinally(int num) {
        try {
            System.out.println(100 / num);
            return 100;
        } catch (Exception e) {
            System.out.println("catch执行...");
            return 200;
        } finally {
            System.out.println("finally执行...");
            return 300;
        }
    }

    @Test
    public void returnTime() {
        System.out.println(returnInTryOrCatchWithBase(0));
        System.out.println(Arrays.toString(returnInTryOrCatchWithReference(0)));
        System.out.println(returnInTryOrCatchAndFinally(0));
    }
}
